package com.example.netty.解决拆包粘包问题;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * 存在粘包问题
 * @author liupk
 * @date 2018/10/24
 */
public class FirstServerHandle extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channel 有数据可读");
        /**服务端读数据*/
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("客户端取出数据为"+byteBuf.toString(Charset.forName("utf-8")));
        /**服务端写数据*/
        /**获取二进制对象*/
//        ByteBuf buffer = ctx.alloc().buffer();
//        byte[] bytes = "写不完的代码，掉不尽的头发".getBytes(Charset.forName("utf-8"));
//        buffer.writeBytes(bytes);
//        ctx.channel().writeAndFlush(buffer);
    }
    
    
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 绑定到线程");
        super.channelRegistered(ctx);
    }
    
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 注销绑定");
        super.channelUnregistered(ctx);
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 准备就绪");
        super.channelActive(ctx);
    }
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 被关闭");
        super.channelInactive(ctx);
    }

    @Override
    public boolean isSharable() {
        return super.isSharable();
    }
    
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
    }
    
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);
    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("当前channel 中数据已经读完");
        super.channelReadComplete(ctx);
    }
    
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("空闲连接超时触发");
        super.userEventTriggered(ctx, evt);
    }
    
    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 从可写状态变更时候调用");
        super.channelWritabilityChanged(ctx);
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常时候调用");
        super.exceptionCaught(ctx, cause);
    }
}